<template>
  <div class="article">
    <div class="main">
      <div class="header">
        <el-form :inline="true" class="form">
          <el-form-item label="文章标题">
            <el-input placeholder="请输入文章标题" v-model="findArticle.title"></el-input>
          </el-form-item>
          <el-form-item label="文章分类">
            <el-select
              placeholder="请选择"
              clearable
              v-model="findArticle.categoryId"
              @focus="getCategoryList"
            >
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章状态">
            <el-select placeholder="请选择" clearable v-model="findArticle.status">
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="find">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="replace">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="deleteBatch()">
              <el-icon><Minus /></el-icon><span>批量删除</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="router.push(`/addArticle/${-1}`)">
              <el-icon><Plus /></el-icon><span>新增文章</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="info" v-if="articleList.length > 0">
        <el-table row-key="id" :data="articleList" stripe @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="文章标题" prop="title" show-overflow-tooltip></el-table-column>
          <el-table-column label="文章标签" prop="tags">
            <template #default="scope">
              <template v-for="item in scope.row.tags" :key="item.id">
                <el-tag style="margin-top: 3px">{{ item.name }}</el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="浏览量" prop="viewCount"></el-table-column>
          <el-table-column label="文章分类" prop="categoryName"></el-table-column>
          <el-table-column label="评论数量" prop="commentCount"></el-table-column>
          <el-table-column label="点赞数量" prop="likeCount"></el-table-column>
          <el-table-column label="是否置顶" prop="isTop">
            <template #default="scope">
              <span
                :class="scope.row.isTop == 0 ? 'blur' : 'red'"
                @click="updateStatusBatch(1, scope.row.isTop == 0 ? 1 : 0, scope.row.id)"
              >
                {{ scope.row.isTop == 0 ? '置顶' : '取消置顶' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="是否推荐" prop="isRecommend">
            <template #default="scope">
              <span
                :class="scope.row.isRecommend == 0 ? 'blur' : 'red'"
                @click="updateStatusBatch(2, scope.row.isRecommend == 0 ? 1 : 0, scope.row.id)"
              >
                {{ scope.row.isRecommend == 0 ? '推荐' : '取消推荐' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="更新状态" prop="latest">
            <template #default="scope">
              <span
                :class="scope.row.latest == 0 ? 'blur' : 'red'"
                @click="updateStatusBatch(3, scope.row.latest == 0 ? 1 : 0, scope.row.id)"
              >
                {{ scope.row.latest == 0 ? '最近更新' : '否' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status">
            <template #default="scope">
              <span
                :class="computedStatusColor(scope.row.status)"
                @click="updateStatusBatch(4, scope.row.status == 0 ? 1 : 0, scope.row.id)"
              >
                {{ computedStatus(scope.row.status) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            prop="createTime"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="修改时间"
            prop="updateTime"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button
                size="small"
                :text="true"
                style="color: #37b4fd"
                @click="router.push(`/addArticle/${scope.row.id}`)"
                >编辑</el-button
              >
              <el-button
                size="small"
                :text="true"
                style="color: red"
                @click="deleteBatch(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-empty v-else :image-size="450"></el-empty>
      <div class="page">
        <el-pagination
          v-model:current-page="findArticle.page"
          v-model:page-size="findArticle.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { Plus, Minus } from '@element-plus/icons-vue'
import { computed, onMounted, ref, toRaw } from 'vue'
import { useRouter } from 'vue-router'
import {
  getArticleListPageService,
  deleteBatchArticle,
  updateStatusBatchService,
} from '@/api/Articles'
import { getCategoryListService } from '@/api/Category'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 条件查询参数
const findArticle = ref({
  page: 1,
  pageSize: 10,
  title: '',
  categoryId: null,
  status: '',
})

// 多条件修改文章状态
const updateStatusBatchInfo = ref({
  isTop: null, // 是否置显示
  isRecommend: null, // 是否推荐
  latest: null, // 更新状态
  status: null, // 文章状态
})

// 分类数据
const categoryList = ref([])

// 定义删除对象传递给后端的数组
const articleIdList = ref([])

// 分页相关
const handleSizeChange = (pageSize) => {
  findArticle.value.pageSize = pageSize
  getArticleList(findArticle.value)
}
const handleCurrentChange = (page) => {
  findArticle.value.page = page
  getArticleList(findArticle.value)
}

const handleSelectionChange = (row) => {
  const obj = JSON.parse(JSON.stringify(row))
  articleIdList.value = []
  obj.forEach((item) => {
    articleIdList.value.push(item.id)
  })
}

const total = ref(null)
const articleList = ref([])

// 根据条件查询文章数据
const find = () => {
  getArticleList(findArticle.value)
}

// 重置按钮
const replace = () => {
  getArticleList({
    page: 1,
    pageSize: 10,
    title: '',
    categoryId: null,
    status: '',
  })
}
// 删除
const deleteBatch = (id) => {
  if (id !== undefined) {
    // 删除单条数据
    ElMessageBox.confirm('你确认删除该条数据吗?', 'Warning', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      appendTo: document.body,
    }).then(async () => {
      const res = await deleteBatchArticle([id])
      await getArticleList(findArticle.value)
    })
  } else {
    // 批量删除
    if (articleIdList.value.length == 0) {
      ElMessage.error('未选中数据')
    } else {
      ElMessageBox.confirm(`你确认删除这${articleIdList.value.length}条数据吗?`, 'Aarning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        appendTo: document.body,
      }).then(async () => {
        const res = await deleteBatchArticle(articleIdList.value)
        await getArticleList(findArticle.value)
      })
    }
  }
}

const computedStatus = (status) => {
  if (status === 1) {
    return '禁用'
  } else if (status === 0) {
    return '启用'
  } else {
    return '草稿'
  }
}
const computedStatusColor = (status) => {
  if (status === 1) {
    return 'red'
  } else if (status === 0) {
    return 'blur'
  } else {
    return 'green'
  }
}

/**
 * 条件查询文章数据接口
 * @param obj
 */
const getArticleList = async (obj) => {
  const { data } = await getArticleListPageService(obj)
  articleList.value = data.records
  total.value = data.total
}
/**
 * 查询分类数据
 */
const getCategoryList = async () => {
  const { data } = await getCategoryListService()
  categoryList.value = data
}
/**
 * 多条件修改文章多种状态
 * @param index 1置顶状态、2推荐状态、3更新状态、4文章状态
 * @param value
 */
const updateStatusBatch = (index, value, articleId) => {
  articleId = parseInt(articleId)
  switch (index) {
    case 1:
      updateStatusBatchInfo.value.isTop = value
      updateStatusService(updateStatusBatchInfo.value, articleId).then(() => {
        updateStatusBatchInfo.value.isTop = null
        getArticleList(findArticle.value)
      })
      break
    case 2:
      updateStatusBatchInfo.value.isRecommend = value
      updateStatusService(updateStatusBatchInfo.value, articleId).then(() => {
        updateStatusBatchInfo.value.isRecommend = null
        getArticleList(findArticle.value)
      })
      break
    case 3:
      updateStatusBatchInfo.value.latest = value
      updateStatusService(updateStatusBatchInfo.value, articleId).then(() => {
        updateStatusBatchInfo.value.latest = null
        getArticleList(findArticle.value)
      })
      break
    case 4:
      updateStatusBatchInfo.value.status = value
      updateStatusService(updateStatusBatchInfo.value, articleId).then(() => {
        updateStatusBatchInfo.value.status = null
        getArticleList(findArticle.value)
      })
      break
  }
}
const updateStatusService = async (value, articleId) => {
  const res = await updateStatusBatchService(value, articleId)
  console.log(res)
}

onMounted(() => {
  getArticleList(findArticle.value)
})
</script>

<style lang="scss" scoped>
.article {
  min-height: 100vh;
  padding: 15px;
  background-color: #f3f4f5;

  .main {
    min-height: 100vh;
    padding: 20px;
    border-radius: 7px;
    background-color: #fff;

    .header {
      margin-top: 15px;
      height: 50px;
      display: flex;
      gap: 15px;
      align-items: center;

      .form {
        :deep(.el-select__wrapper) {
          width: 150px;
        }
      }
    }
  }

  .info {
    padding-top: 25px;
  }

  .page {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

.blur {
  cursor: pointer;
  color: #37b4fd;
}
.red {
  cursor: pointer;
  color: red;
}
.green {
  color: #43e478;
  pointer-events: none;
}

::v-deep.el-table .cell {
  text-align: center !important;
}
</style>